package com.nononsenseapps.feeder.processor.interceptor

import com.nononsenseapps.feeder.db.entity.FeedItem
import com.nononsenseapps.feeder.db.entity.FeedItemPreLoadItem
import com.nononsenseapps.feeder.db.room.*
import com.nononsenseapps.feeder.processor.Interceptor
import com.nononsenseapps.feeder.util.naiveFindImageLinkList

class PreLoaderItemsInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): FeedItem {
        val feed=chain.getFeed()
        val feedItem=chain.getFeedItem()
        val feedItemPreLoadItemDao=chain.getAppDatabase().feedItemPreLoadItemDao()
        //val context=chain.getProcessContext()

        feedItem.enclosureFilename?.let{
             if(feed.preDownload){
               var preLoadItem = feedItemPreLoadItemDao.findEnclosureLoadItem(feedItem.id)
                 if(preLoadItem==null) {
                     preLoadItem = FeedItemPreLoadItem(
                         itemId = feedItem.id,
                         preLoadUrl = feedItem.enclosureLink!!,
                         isEnclosure = true
                     )
                     feedItemPreLoadItemDao.insert(preLoadItem)
                 }
            }
        }

        if(feed.imagePreDownload&&feedItem.image_count>0){
            naiveFindImageLinkList(feedItem.description)?.forEach {
                val preLoadItem = FeedItemPreLoadItem(itemId=feedItem.id,preLoadUrl = it, isEnclosure = false)
                feedItemPreLoadItemDao.insert(preLoadItem)
            }
        }
        return chain.proceed(feed, feedItem)
    }
}
